package com.qlylkj.lbk.ui.user.authentication

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.qlylkj.lbk.app.PreferenceHelper
import com.qlylkj.lbk.base.BaseViewModel
import com.qlylkj.lbk.model.api.ResultResponse
import com.qlylkj.lbk.model.repository.AuthRepository
import com.qlylkj.lbk.model.repository.CommonRepository
import com.qlylkj.lbk.model.repository.UserRepository
import java.io.File

class IdentityAuthViewModel: BaseViewModel(){

    private val _uiState = MutableLiveData<AuthUiModel>()
    val uiState: LiveData<AuthUiModel>
        get() = _uiState

    private val _uploadUiState = MutableLiveData<UploadUiModel>()
    val uploadUiState: LiveData<UploadUiModel>
        get() = _uploadUiState

    private val commonRepository by lazy { CommonRepository() }

    private val userRepository by lazy { UserRepository() }

    private val authRepository by lazy { AuthRepository() }

    private fun emitUiState(
        showError: String? = null,
        identityAuthSuccess: Boolean = false
    ) {
        val uiModel = AuthUiModel(showError,identityAuthSuccess)
        _uiState.value = uiModel
    }

    private fun uploadEmitUiState(
        showError: String? = null,
        type: String = "",
        uploadUrl: String? = null
    ) {
        val uiModel = UploadUiModel(showError, type, uploadUrl)
        _uploadUiState.value = uiModel
    }


    data class AuthUiModel(
        val showError: String?,
        val identityAuthSuccess: Boolean
    )

    data class UploadUiModel(
        val showError: String?,
        val type: String,
        val uploadUrl: String?
    )

    fun uploadFile(type: String, uploadFile: File) {
        launch {
            val result = commonRepository.uploadFile(uploadFile)
            if (result is ResultResponse.SuccessEntity) {
                uploadEmitUiState(type = type, uploadUrl = result.data)
            } else if (result is ResultResponse.Error) {
                uploadEmitUiState(showError = result.exception.message)
            }
        }
    }

    fun identityAuth(options: MutableMap<String,Any>){
        launch {
            val result = authRepository.identityAuth(options)
            if (result is ResultResponse.Success) {
                getUserInfo()
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }

    private fun getUserInfo(){
        launch {
            val result = userRepository.getUserInfo()
            if (result is ResultResponse.SuccessEntity) {
                PreferenceHelper.setUserInfo(result.data)
                emitUiState(identityAuthSuccess = true)
            } else if (result is ResultResponse.Error) {
                emitUiState(showError = result.exception.message)
            }
        }
    }

}